import json
from flask import (Blueprint, request, session)
from flaskr import Utils
from flaskr.server.SheetsServer import *
bp = Blueprint('changeFieldName',__name__, url_prefix='/changeFieldName')

@bp.route('', methods = ['POST'])
def changeFieldName():
    sheet_name = request.json.get('sheetName')
    old_field = request.json.get('oldField')
    new_field = request.json.get('newField')
    has_change = False
    # sheets = []
    #
    # if('sheets' in session.keys()):
    #     sheets = session['sheets']
    #
    # for sheet in sheets:
    #     if(sheet['showName'] == sheet_name):
    #         sheet_json = json.loads(sheet['json'])
    #
    #         # sheet_json[new_field] = sheet_json[old_field] #添加新的字段名
    #
    #         columns = sheet_json['columns']
    #         index = columns.index(old_field)
    #         columns[index] = new_field
    #
    #         sheet_json['columns'] = columns
    #
    #         # del sheet_json[old_field] #删除之前的字段
    #
    #         sheet_json = json.dumps(sheet_json)
    #
    #         df = Utils.jsonToDataFrame(sheet_json)
    #
    #         sheet['json'] = sheet_json
    #         sheet['columns'] = Utils.getColumns(df) #重新获取所有字段
    #         sheet['table'] = Utils.dataFrameToHtml(df) #重新获取表
    #         session['sheets'] = sheets
    #         has_change = True
    #
    #         break
    sheet = get_sheet(sheet_name)

    if sheet:
        df = get_dataframe(sheet_name)

        columns = getColumns(df) #添加新的字段名

        index = columns.index(old_field)
        columns[index] = new_field

        df.columns = columns

        if 'md5' in sheet.keys():
            setPkl(df, sheet['md5'])
            df = df.head(200)

        sheet['json'] = dataFrameToJson(df)
        sheet['columns'] = Utils.getColumns(df) #重新获取所有字段
        sheet['table'] = Utils.dataFrameToHtml(df) #重新获取表

        set_sheet(sheet_name, sheet)
        has_change = True

    if has_change:
        return {
            'code': 200,
            'msg': '更改成功',
            'data': sheet
        }

    else:
        return{
            'code' : 500,
            'msg' : '修改失败'
        }
